<!--
 * @Author: Neko
 * @Date: 2021-05-21 15:33:38
 * @LastEditTime: 2021-05-28 13:31:22
 * @LastEditors: Neko
-->
<template>
  <view>
    <view v-if="type === 1" class="detail__title">
      <template
        v-if="(!businessData.auditStatus) || businessData.auditStatus === 0 || businessData.auditStatus === -2"
      >
        {{ $t('locales.applyingBusiness1') }}
        <text class="shop">{{ storeData.storeName }}</text>
        {{ $t('locales.applyingBusiness2') }}
        {{ $t('locales.fillForm') }}
      </template>
      <template v-if="businessData.auditStatus === 1">
        {{ $t('locales.congratulation') }} {{ $t('locales.appliedResult5') }}<text class="shop">{{ storeData.storeName }}</text> {{ $t('locales.appliedResult2') }}
      </template>
      <template v-if="businessData.auditStatus === -1">{{ $t('locales.regret') }}{{ $t('locales.appliedResult1') }} <text class="shop">{{ storeData.storeName }}</text> {{ $t('locales.appliedResult3') }}</template>
    </view>

    <u-form
      :model="formData"
      ref="form"
      label-position="top"
      :label-style="{ fontWeight: 'bolder', fontSize: '28rpx' }"
      :border-bottom="false"
    >
      <u-form-item :label="$t('locales.enterpriseName')" :border-bottom="false" prop="distributorName" label-width="150" :label-position="isDisabled ? 'left' : 'top'">
        <u-input v-if="!isDisabled" v-model="formData.distributorName" class="detail__input" />
        <text v-else>{{ formData.distributorName }}</text>
      </u-form-item>

      <u-form-item :label="$t('locales.enterpriseLisence')" :border-bottom="false" prop="businessLicense">
        <u-upload
          :show-progress="false"
          custom-btn
          width="120"
          height="120"
          max-count="1"
          :max-size="3145728"
          :action="baseUrl + '/file/upload'"
          :file-list="fileList"
          :deletable="!isDisabled"
          del-bg-color="#999"
          @on-uploaded="uploadSuccess"
          @on-remove="uploadRemove"
          @on-choose-complete="uploadComplete"
          @on-error="uploadError"
          @on-oversize="oversize"
        >
          <view slot="addBtn" class="addBtn">
            <u-icon name="plus" color="#ccc" size="120"></u-icon>
          </view>
        </u-upload>
      </u-form-item>
    </u-form>

    <SubmitBtn v-if="!isDisabled" @click="onClickSubmit" />
  </view>
</template>

<script>
import { baseUrl } from '@/config'
import SubmitBtn from '@/components/submitBtn'
import { handleBusinessSaveAction, handleBusinessUpdateAction, getBusinessDataAction } from '@/api/http/order'
import { getImageUrl } from '@/util'

export default {
  components: {
    SubmitBtn
  },

  props: {
    storeData: {
      type: Object,
      default: () => ({})
    },

    storeId: {
      type: [String, Number],
      default: ''
    },

    type: {
      type: Number,
      default: 1
    },

    businessInfo: {
      type: Object,
      default: () => ({})
    }
  },

  data() {
    const _this = this
    return {
      baseUrl: baseUrl(),

      formData: {
        businessLicense: '',
        distributorName: '',
        // distributorSource: '',
        domainPrefix: '',
        storeId: '',
        // #ifdef APP-PLUS
        terminal: '2',
        // #endif

        // #ifdef H5
        terminal: '1'
        // #endif
        
      },

      businessData: {},

      ruler: {
        businessLicense: [{ required: true, message: _this.$t('locales.change1'), trigger: 'change' }],
        distributorName: [{ required: true, message: _this.$t('locales.blur'), trigger: 'blur' }]
      },

      fileList: [],

      isUploading: false
    }
  },

  computed: {
    domainPrefix() {
      return this.$store.getters.domainPrefix
    },

    isDisabled() {
      return ((this.businessData.auditStatus === 1 || this.businessData.auditStatus === -2) || this.businessData.isOperation === 0) && this.type === 2
    }
  },

  watch: {
    storeData() {
      if (this.type === 2) return
      
      this.getBusinessDataAction()
    },

    businessInfo() {
      if (this.type === 2) {
        this.businessData = this.businessInfo
        this.formData = this.businessInfo

        console.log(this.businessData)

        this.fileList = [{
          url:  this.businessData.businessLicenseUrl,
          name: this.businessData.businessLicense,
          __url: this.businessData.businessLicense
        }]
      }

    }
  },

  mounted() {
    this.$refs.form.setRules(this.ruler)

    // this.getBusinessDataAction()
  },

  onReady() {
    this.$refs.form.setRules(this.ruler)
  },

  methods: {
    // 图片选择完成
    uploadComplete(lists, name) {
      uni.showLoading({
        mask: true
      })
    },
    // 图片上传完成
    uploadSuccess(fileList, goodsId) {
      this.fileList = fileList
      uni.hideLoading()
    },
    // 图片上传失败
    uploadError() {
      uni.hideLoading()
    },
    // 超出大小
    oversize() {
      uni.showModal({
        content: this.$t('locales.overstep'),
        confirmColor: '#0049AC',
        showCancel: false
      })
    },
    // 移除图片
    uploadRemove(index) {
      this.fileList.splice(index, 1)
      this.formData.businessLicense = ''
      uni.hideLoading()
    },

    async getBusinessDataAction() {
      try {
        const res = await getBusinessDataAction({
          storeId: this.storeId,
          domainPrefix: this.domainPrefix
        })

        if (res.code === 200) {
          const data = res.data

          if (!data) return

          this.formData = Object.assign(this.formData, {
            businessLicense: data.businessLicense,
            distributorName: data.distributorName,
            storeId: data.storeId,
            id: data.id
          })

          this.businessData = res.data

          this.fileList = [{ url: data.businessLicenseUrl, name: data.businessLicense, __url: data.businessLicense }]
        } else {
          return uni.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      } catch (e) {
        throw Error(e)
      }
    },

    onClickSubmit() {
      if (this.isUploading) return
      
      this.isUploading = true

      if (this.fileList[0]) {
        this.formData.businessLicense = getImageUrl(this.fileList[0])
      }

      this.$refs.form.validate(isValid => {
        if (isValid) {
          this.handleSaveAction()
        }
      })
    },

    async handleSaveAction() {
      try {
        this.formData.domainPrefix = this.domainPrefix
        this.formData.storeId = this.storeId || this.businessInfo.storeId

        let url

        if (this.formData.id && this.businessData.auditStatus !== -1) {
          url = handleBusinessUpdateAction
        } else {
          url = handleBusinessSaveAction
        }

        const form = this.formData

        const res = await url({
          businessLicense: form.businessLicense,
          distributorName: form.distributorName,
          domainPrefix: form.domainPrefix,
          storeId: form.storeId,
          terminal: form.terminal,
          id: form.id
        })

        if (res.code === 200) {
          this.$emit('confirm')
          this.isUploading = false
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none'
          })
          this.isUploading = false
        }
      } catch (e) {
        this.isUploading = false
        throw Error(e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.detail__input {
  padding: 0 25rpx!important;
  border: 1rpx solid #e6e6e6;
  border-radius: 8rpx;
}

.addBtn {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 280rpx;
  height: 280rpx;
  border: 2rpx solid #F2F2F2;
  border-radius: 8rpx;
  font-weight: normal;
  background: #FAFAFA;
}

/deep/ .u-preview-wrap {
  width: 120px!important;
  height: 120px!important;
}

/deep/ .u-form-item {
  padding: 0;
}

.detail__title {
  margin-bottom: 60rpx;
  font-size: 28rpx;
  color: #666;

  .shop {
    color: #333;
  }
}
</style>